package org.water.garden.receiver;

import org.water.garden.R;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentReceiver;
import android.database.Cursor;
import android.provider.Im.Chats;
import android.provider.Im.Contacts;
import android.provider.Im.Messages;

public class MessageReceiver extends IntentReceiver {

	public final static int NOTFI_CODE_MESSAGE = R.drawable.new_message;
	private NotificationManager notificationManager;

	@Override
	public void onReceiveIntent(Context context, Intent intent) {
		notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);

		Cursor c = context.getContentResolver().query(
				intent.getData(),
				new String[] { Messages._ID, Messages.ACCOUNT,
						Messages.CONTACT, Messages.BODY, Messages.PROVIDER, Messages.SHOW_TIME_STAMP },
				null, null, null);

		if (c.first()) {
			if(c.getInt(5) != 0){
				return;
			}
			StringBuilder sb = new StringBuilder();
			sb.append(Contacts.PROVIDER).append("=? AND ");
			sb.append(Contacts.ACCOUNT).append("=? AND ");
			sb.append(Contacts.USERNAME).append("=?");

			Cursor contactCur = context.getContentResolver().query(
					Contacts.CONTENT_URI,
					new String[] { Contacts._ID, Contacts.NICKNAME },
					sb.toString(),
					new String[] { 
						Integer.toString(c.getInt(4)),
						Integer.toString(c.getInt(1)), 
						c.getString(2) }, null);
			if (contactCur.first()) {
				
				Cursor mc = context.getContentResolver().query(Chats.CONTENT_URI, new String[]{Chats._ID}, Chats.CONTACT_ID + "=?", 
						new String[]{Long.toString(contactCur.getInt(0))}, null);
				
				if(!mc.first()){
					ContentValues values = new ContentValues();
					
					values.put(Chats.CONTACT_ID, contactCur.getInt(0));
					values.put(Chats.GROUP_CHAT, 0);
					
					context.getContentResolver().insert(Chats.CONTENT_URI, values);
				}
				mc.close();
				
				Intent chatIntent = new Intent(Intent.VIEW_ACTION, Chats.CONTENT_URI);
				
				notificationManager.notify(NOTFI_CODE_MESSAGE,
						new Notification(context, R.drawable.new_message, 
								contactCur.getString(1)	+ " 说 " + c.getString(3), 
								System.currentTimeMillis(), "收到新消息", 
								contactCur.getString(1)	+ " 说 " + c.getString(3), chatIntent,
								R.drawable.new_message, "查看新消息", chatIntent));
				contactCur.close();
			}else{
				
			}

			c.close();
		}
	}

}
